package javango.forms.fields;

import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;

import com.google.inject.Inject;

import javango.forms.fields.annotations.CharFieldProperties;
import javango.forms.widgets.TextInputWidget;
import javango.forms.widgets.WidgetFactory;

public class CharField extends AbstractField {

	@Inject
	public CharField(WidgetFactory widgetFactory) {
		super(widgetFactory);
	}

	private Integer maxLength;

	public void handleAnnotation(Annotation annotation) {
		super.handleAnnotation(annotation);
		if (!(annotation instanceof CharFieldProperties)) return;
		
		CharFieldProperties props = (CharFieldProperties)annotation;
		if (props.maxLength() != 0) {
			this.setMaxLength(props.maxLength());
		}
	}
	
	@Override
	public Object clean(String value, Map errors) {
		Object superValue = super.clean(value, errors);
		
		if (superValue == null) return null;
		
		if (getMaxLength() != null && getMaxLength() > 0) {
			if (value.length() > getMaxLength()) {
				errors.put(getName(), "Too Long");
			}
		}
		return value;
	}

	public Integer getMaxLength() {
		return maxLength;
	}

	public void setMaxLength(Integer maxLength) {
		this.maxLength = maxLength;
	}

	@Override
	public Map<String, String> getWidgetAttrs() {
		if (maxLength != null) {
			Map<String, String> attrs = new HashMap<String, String>();
			attrs.put("maxlength", maxLength.toString());
			return attrs;
		}
		return null;
	}
		
}
